package service

import (
	"catering_sys_api/cmd/api/biz/business/model/store"
	"catering_sys_api/cmd/api/dao"
	"catering_sys_api/cmd/api/model"
	"catering_sys_api/core/db"
	"catering_sys_api/core/random_string"
	"context"
	"errors"

	"github.com/cloudwego/hertz/pkg/app"
	"gorm.io/gorm"
)

type StoreService struct {
	ctx context.Context
	c   *app.RequestContext
}

func NewStoreService(ctx context.Context, c *app.RequestContext) *StoreService {
	return &StoreService{
		ctx: ctx,
		c:   c,
	}
}

func (s *StoreService) List(request store.ListRequest) (list []store.ListResponse, pagination *model.Pagination, err error) {
	var (
		storeDao                 *dao.StoreDao
		businessUserDao          *dao.BusinessUserDao
		businessUserVo           dao.BusinessUserVo
		storeHasOneStoreUserList []model.StoreHasOneStoreUser
	)

	storeDao = dao.NewStoreDao(s.ctx)
	businessUserVo, err = businessUserDao.GetBusinessUserVoFromC(s.c)
	storeHasOneStoreUserList, pagination, err = storeDao.GetStoreHasOneStoreUserListByBusinessId(businessUserVo.BusinessID, request.Page, request.PageSize)
	for _, v := range storeHasOneStoreUserList {
		list = append(list, store.ListResponse{
			ID:            v.ID,
			StoreName:     v.StoreName,
			StoreStatus:   v.StoreStatus,
			StoreLocation: v.StoreLocation,
			Phone:         v.StoreUser.Phone,
			StoreUserId:   v.StoreUser.ID,
			LastTime:      v.LastTime,
			AddTime:       v.AddTime,
		})
	}
	if list == nil {
		list = make([]store.ListResponse, 0)
	}
	return
}

func (s *StoreService) Add(request store.AddRequest) (err error) {
	var (
		salt string

		businessDao     *dao.BusinessDao
		businessUserDao *dao.BusinessUserDao
		storeDao        *dao.StoreDao
		storeUserDao    *dao.StoreUserDao

		businessUserVo dao.BusinessUserVo
		business       model.Business
		store          model.Store
		storeUser      model.StoreUser
		storeList      []model.Store
	)
	businessDao = dao.NewBusinessDao(s.ctx)
	businessUserDao = dao.NewBusinessUserDao(s.ctx)
	businessUserVo, err = businessUserDao.GetBusinessUserVoFromC(s.c)
	if err != nil {
		return
	}
	//1.检查该商户平台创建的店铺的个数是否超过上线
	business, err = businessDao.GetBusinessByBusinessId(businessUserVo.BusinessID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该商户不存在")
		return
	}
	if err != nil {
		return
	}

	if business.Status == model.BusinessStatusDisable {
		err = errors.New("该商户已被禁用")
		return
	}
	//获取店铺数量是否超过限制
	storeDao = dao.NewStoreDao(s.ctx)
	storeList, err = storeDao.GetStoreListByBusinessId(businessUserVo.BusinessID)
	if err != nil {
		return
	}
	if business.StoreNum <= len(storeList) {
		err = errors.New("门店数量超出，请购买席位")
		return
	}
	//2.检查店铺名字在改商户是否已经存在
	for _, v := range storeList {
		if v.StoreName == request.StoreName {
			err = errors.New("该店铺名字已经在该商户平台存在，请更换其他名字")
			return
		}
	}
	//3.检查该手机号是否已经注册过商铺号 已经注册过的，不能再次注册（一个手机号对应一个商铺平台）
	storeUserDao = dao.NewStoreUserDao(s.ctx)
	storeUser, err = storeUserDao.GetStoreUserByPhone(request.Phone)

	if errors.Is(err, gorm.ErrRecordNotFound) {
		//该手机号码没有被注册过
		//添加商铺账号
		store = model.Store{
			StoreName:     request.StoreName,         // 店铺名字
			StoreStatus:   request.StoreStatus,       // 店铺状态
			StoreDesc:     request.StoreDesc,         // 店铺简介
			BusinessID:    businessUserVo.BusinessID, // 商家ID
			StoreLocation: request.StoreLocation,     // 地址
		}

		tx := db.DB.Begin()
		salt = random_string.RandStr(6)
		err = storeDao.AddStore(&store, tx)
		storeUser = model.StoreUser{
			UserName: "",
			Phone:    request.Phone,
			StoreID:  store.ID,
			Password: genPwd(request.Password, salt),
			Salt:     salt,
		}
		if err != nil {
			tx.Rollback()
			return
		}
		err = storeUserDao.AddStoreUser(&storeUser, tx)
		if err != nil {
			tx.Rollback()
			return
		}
		tx.Commit()
		return
	}

	if err == nil {
		err = errors.New("该手机号已经注册过商户号，请更换手机号")
	}
	return

}

func (p *StoreService) Update(request store.UpdateRequest) (err error) {
	var (
		storeDao        *dao.StoreDao
		storeUserDao    *dao.StoreUserDao
		businessUserDao *dao.BusinessUserDao
		businessUserVo  dao.BusinessUserVo
		store           model.Store
		storeUser       model.StoreUser
	)

	businessUserDao = dao.NewBusinessUserDao(p.ctx)
	businessUserVo, err = businessUserDao.GetBusinessUserVoFromC(p.c)
	if err != nil {
		return
	}
	//1.检查该商铺是否存在
	storeDao = dao.NewStoreDao(p.ctx)
	store, err = storeDao.GetStoreByStoreIdAndBusinessId(request.StoreId, businessUserVo.BusinessID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该商铺不存在")
		return
	}

	if err != nil {
		return
	}
	//2.检测店铺用户是否存在
	storeUserDao = dao.NewStoreUserDao(p.ctx)
	storeUser, err = storeUserDao.GetStoreUserByUserId(request.StoreUserId)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该用户不存在")
		return
	}
	if err != nil {
		return
	}
	if storeUser.StoreID != store.ID {
		err = errors.New("非法的请求")
		return
	}
	if storeUser.Phone != request.Phone {
		//手机号码不一致 说明修改了手机号  检测新的手机号码是否已经注册过
		_, err = storeUserDao.GetStoreUserByPhone(request.Phone)
		if !errors.Is(err, gorm.ErrRecordNotFound) && err != nil {
			return
		}
		if err == nil {
			err = errors.New("该手机号已经注册过商铺号，请更换手机号")
			return
		}

	}

	store.StoreName = request.StoreName
	store.StoreStatus = request.StoreStatus
	store.StoreDesc = request.StoreDesc
	store.StoreLocation = request.StoreLocation

	storeUser.Phone = request.Phone
	//更新用户信息
	tx := db.DB.Begin()
	err = storeDao.UpdateStoreByStoreIdAndBusinessId(store, tx)
	if err != nil {
		tx.Rollback()
		return
	}

	err = storeUserDao.UpdateStoreUser(storeUser, tx)
	if err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()

	return
}

func (p *StoreService) Detail(request store.DetailRequest) (response store.DetailResponse, err error) {
	var (
		storeDao        *dao.StoreDao
		storeUserDao    *dao.StoreUserDao
		businessUserDao *dao.BusinessUserDao
		businessUserVo  dao.BusinessUserVo
		store           model.Store
		storeUser       model.StoreUser
	)
	businessUserDao = dao.NewBusinessUserDao(p.ctx)
	businessUserVo, err = businessUserDao.GetBusinessUserVoFromC(p.c)
	if err != nil {
		return
	}
	//1.检查该商铺是否存在
	storeDao = dao.NewStoreDao(p.ctx)
	store, err = storeDao.GetStoreByStoreIdAndBusinessId(request.StoreId, businessUserVo.BusinessID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该商铺不存在")
		return
	}
	if err != nil {
		return
	}
	storeUser, err = storeUserDao.GetStoreUserByUserId(request.StoreUserId)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该用户不存在")
		return
	}
	if err != nil {
		return
	}
	response.StoreId = store.ID
	response.StoreName = store.StoreName
	response.StoreStatus = store.StoreStatus
	response.StoreLocation = store.StoreLocation
	response.StoreDesc = store.StoreDesc
	response.Phone = storeUser.Phone
	response.AddTime = store.AddTime
	response.LastTime = store.LastTime
	return
}

func (p *StoreService) State(request store.StateRequest) (err error) {
	var (
		storeDao        *dao.StoreDao
		businessUserDao *dao.BusinessUserDao
		businessUserVo  dao.BusinessUserVo
		store           model.Store
	)
	businessUserDao = dao.NewBusinessUserDao(p.ctx)
	businessUserVo, err = businessUserDao.GetBusinessUserVoFromC(p.c)
	if err != nil {
		return
	}
	//1.检查该商铺是否存在
	storeDao = dao.NewStoreDao(p.ctx)
	store, err = storeDao.GetStoreByStoreIdAndBusinessId(request.StoreId, businessUserVo.BusinessID)
	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = errors.New("该商铺不存在")
		return
	}
	if err != nil {
		return
	}
	//更新商铺状态
	if err != nil {
		return
	}
	store.StoreStatus = request.StoreStatus

	err = storeDao.UpdateStoreByStoreIdAndBusinessId(store, db.DB)
	return
}
